﻿﻿/* =====================================================================================================================
  * Author - Sachin Sharma
  * Copyright (c) 2012 Sachin Sharma (3screator.com). All rights reserved.
  * Follows most coding rules. However, due to time constraint you will see some hard coding or rules not strictly followed
=====================================================================================================================*/
#include "pch.h"
#include "SpellChecker.h"
#include "SpellingClient.h"

using namespace SpellCheckerWrapperComponent;
using namespace Platform;
using namespace Windows::Foundation::Collections;
using namespace Platform::Collections;
using namespace Windows::Foundation::Collections;
using namespace std;

SpellChecker::SpellChecker()
{
	_Errors = ref new Vector<String^>();
}



void copyToManagedVector(std::vector<PCWSTR>& vector, std::vector<String^>& managedVector)
{
	size_t size = vector.size();
	for(size_t i = 0; i < size; i++)
    {
		String^ item = ref new String(vector[i]);
		managedVector.push_back(item);
    }    
}

IVector<String^>^ SpellChecker::GetSupportedLanguages()
{
	std::vector<PCWSTR> vectorAvailableLanguages;
	std::vector<String^> managedVector;
	try
	{
		// Reset errors
		Errors->Clear();

		// Get supported languages
		int success = GetAvailableLanguages(vectorAvailableLanguages);
		if (gVectorErrors.size() == 0)
		{
			_LastValue = vectorAvailableLanguages.size(); /*wchar_t wcSize [MAX_PATH]; _itow_s(_LastValue, wcSize, MAX_PATH, 10); Errors->Append(ref new String(wcSize));*/			
			copyToManagedVector(vectorAvailableLanguages, managedVector);
		}
	}
	catch(Exception^ ex)
	{
		Errors->Append(ex->Message);
	}
	return ref new Vector<String^>(std::move(managedVector));
}

SpellingCheckResults^ SpellChecker::CheckWordSpelling(String^ word, String^ languageTag)
{
	SpellingCheckResults^ spellingCheckResults = ref new SpellingCheckResults();
	std::vector<PCWSTR> vectorSuggestions;
	std::vector<String^> managedVector;
	try
	{
		//PCWSTR languageTag = L"en-US";
		bool isSpellingCorrect = false;
		PWSTR replacement = L"";
		int success = CheckSpelling(word->Data(), languageTag->Data(), isSpellingCorrect, vectorSuggestions, replacement);
		if (gVectorErrors.size() == 0)
		{
			copyToManagedVector(vectorSuggestions, managedVector);
			spellingCheckResults->IsCorrect = isSpellingCorrect;
			spellingCheckResults->Suggestions = ref new Vector<String^>(std::move(managedVector));
			spellingCheckResults->ReplacementIfAny = ref new String(replacement);;
		}
	}
	catch(Exception^ ex)
	{
		Errors->Append(ex->Message);
	}
	return spellingCheckResults;
}
